package cn.daniellee.plugin.rs.core;

import cn.daniellee.plugin.rs.RestrictedShop;
import cn.daniellee.plugin.rs.component.ItemGenerator;
import cn.daniellee.plugin.rs.model.PlayerData;
import cn.daniellee.plugin.rs.model.Shop;
import cn.daniellee.plugin.rs.model.ShopItem;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ShopCore {

	public static ConcurrentHashMap<String, Shop> SHOPS = new ConcurrentHashMap<>();

	public static ConcurrentHashMap<String, PlayerData> TRADING = new ConcurrentHashMap<>();

	public static PlayerData GeneratePlayerDataByShop(Player player, Shop shop) {
		PlayerData playerData = new PlayerData();
		playerData.setName(player.getName());
		playerData.setShop(shop.getName());
		playerData.setCheckSum(shop.getCheckSum());
		// 计算可售数量
		List<Integer> indexList = new ArrayList<>();
		List<Integer> purchaseNumbers = new ArrayList<>();
		// 将权重值组合为数组
		Integer[] weights = shop.getPurchaseItems().stream().map(ShopItem::getWeight).toList().toArray(new Integer[]{});
		int totalWeight = Arrays.stream(weights).reduce(0, Integer::sum);
		int itemLeft = weights.length;
		for (int i = 0; i < itemLeft && i <= shop.getMaxShowNumber(); i++) {
			int randNext = new Random().nextInt(totalWeight + 1);
			for (int j = 0; j < weights.length; j++) {
				if (randNext <= weights[j]) {
					// 随机到之后，权重清零
					totalWeight -= weights[j];
					weights[j] = -1;
					itemLeft -= 1;
					// 记录商品下标
					indexList.add(j);
					// 随机可售数量
					purchaseNumbers.add(new Random().nextInt(shop.getPurchaseItems().get(j).getQuantityRange()[0], shop.getPurchaseItems().get(j).getQuantityRange()[1] + 1));
					break;
				} else if (weights[j] != -1) {
					randNext -= weights[j];
				}
			}
		}
		playerData.setIndexList(indexList.toArray(new Integer[]{}));
		playerData.setPurchaseNumbers(purchaseNumbers.toArray(new Integer[]{}));
		// 初始化已售数量
		Integer[] soldNumbers = new Integer[indexList.size()];
		Arrays.fill(soldNumbers, 0);
		playerData.setSoldNumbers(soldNumbers);
		// 查询会员组
		RestrictedShop.getInstance().getPrivileges().forEach(item -> {
			if (player.hasPermission("rshop.privilege." + item.getSuffix())) {
				playerData.setPercentage(item.getPercentage());
			}
		});
		// 写入创建时间
		playerData.setGenerateAt(System.currentTimeMillis());
		return playerData;
	}

	public static ItemStack generateShopItem(ShopItem shopItem, int sellableNumber, int soldNumber, int percentage) {
		// 计算每个出售的价格衰减
		double currentPrice = 0;
		if (sellableNumber > 0) {
			double attenuation = ((double) (shopItem.getPriceRange()[1] - shopItem.getPriceRange()[0])) / ((double) (shopItem.getQuantityRange()[1] * (100 + percentage) / 100));
			currentPrice = ((double) shopItem.getPriceRange()[1]) - attenuation * ((double) soldNumber);
		}
		List<String> lore = RestrictedShop.getInstance().getConfig().getStringList("menu.item-description");
		if (lore.isEmpty()) {
			lore.add("&ePrice：&b{currentPrice}");
			lore.add("&eLeft click to sell one");
			lore.add("&eShift+Left click Sell all");
		}
		double finalCurrentPrice = currentPrice;
		lore.replaceAll(item -> item.replace("{currentPrice}", finalCurrentPrice > 0 ? new DecimalFormat("#.00").format(finalCurrentPrice) : "-"));
		return ItemGenerator.getItem(shopItem.getDisplayName(), lore, shopItem.getMaterial(), shopItem.getCustomerModelData(), sellableNumber > 0 ? sellableNumber : 1);
	}
}
